package com.ruanda.config;

import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration {

    @Autowired
    private SwaggerProperties swaggerProperties;

    /**
     * 项目环境对象
     */
    @Autowired
    private Environment environment;

    /**
     * 设置swagger文档对象
     * 1.swagger文档只有在开发阶段生成，生产环境不需要生成文档
     *
     * @return
     */
    @Bean
    public OpenAPI springShopOpenAPI() {
        // 生成文档的开关，true默认开启状态
        Boolean flag = true;
        // 从项目环境对象中获取项目运行环境标识
        String[] activeProfiles = environment.getActiveProfiles();
        // 循环遍历
        for (String activeProfile : activeProfiles) {
            if (activeProfile.equals("pro")) {
                // pro一般表示生产环境
                flag = false;
                break;
            }
        }
        if (!flag) {
            return null;
        }
        return new OpenAPI()
                .info(new Info()
                        .title(swaggerProperties.getTitle())
                        .description(swaggerProperties.getDescription())
                        .version(swaggerProperties.getVersion())
                        .license(new License().name(swaggerProperties.getName()).url(swaggerProperties.getUrl())))
                .externalDocs(new ExternalDocumentation()
                        .description(swaggerProperties.getLicense())
                        .url(swaggerProperties.getLicenseUrl()));
    }


}